//
//  YNSDatePickerView.m
//  DataPickerTest
//
//  Created by 俞乃胜 on 2023/12/13.
//

#import "YNSDatePickerView.h"
//屏幕宽度
#define screenWigth [[UIScreen mainScreen] bounds].size.width
//屏幕高度
#define screenHeight [[UIScreen mainScreen] bounds].size.height
@interface YNSDatePickerView()<UIPickerViewDataSource, UIPickerViewDelegate>
@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) NSArray *years;
@property (nonatomic, strong) NSArray *tianGanArray;
@property (nonatomic, strong) NSArray *diZhiArray;
@property (nonatomic, strong) NSMutableArray *nongliYears;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSArray *nongLiMonths;
@property (nonatomic, strong) NSArray *nongLiDays;
@property (nonatomic, strong) NSArray *yangLiMonths;
@property (nonatomic, strong) NSArray *yangLiDays;

@property (nonatomic, strong)NSDate *currentDate;
@property (nonatomic, assign) BOOL showYear;
@property (nonatomic, assign) BOOL isNongLi;

@end
@implementation YNSDatePickerView

- (instancetype)initWithFrame:(CGRect)frame{
    
    
    self = [super initWithFrame:frame];
    if(self){
        
        self.backgroundColor = [UIColor lightGrayColor];
        self.showYear = NO;
        self.isNongLi = NO;
        self.dataArray =[[NSMutableArray alloc]init];
        self.currentDate = [NSDate date];
        UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"公历", @"农历"]];
        segmentedControl.frame = CGRectMake(10, 10, 100, 30);
        segmentedControl.selectedSegmentIndex = 0;
        [segmentedControl addTarget:self action:@selector(segmentedControlValueChanged:) forControlEvents:UIControlEventValueChanged];
        
        [self addSubview:segmentedControl];
        
        
        UIButton *but =[[UIButton alloc]initWithFrame:CGRectMake(120, 5, 100, 40)];
        [self addSubview:but];
        [but setTitle:@"忽略年份" forState:UIControlStateNormal];
        [but setTitle:@"显示年份" forState:UIControlStateSelected];
        but.titleLabel.font = [UIFont systemFontOfSize:16];
        but.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [but addTarget:self action:@selector(changeSelect:) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton *quedingBut =[[UIButton alloc]initWithFrame:CGRectMake(screenWigth-120, 5, 100, 40)];
        [self addSubview:quedingBut];
        [quedingBut setTitle:@"确定" forState:UIControlStateNormal];
        quedingBut.titleLabel.font = [UIFont systemFontOfSize:16];
        quedingBut.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [quedingBut addTarget:self action:@selector(queding) forControlEvents:UIControlEventTouchUpInside];
        
        
        
        self.nongliYears = [[NSMutableArray alloc]init];
        self.tianGanArray = @[@"甲", @"乙", @"丙", @"丁", @"戊", @"己", @"庚", @"辛", @"壬", @"癸"];
        self.diZhiArray = @[@"子", @"丑", @"寅", @"卯", @"辰", @"巳", @"午", @"未", @"申", @"酉", @"戌", @"亥"];
        self.years = [self generateYearsArray]; // 生成一定范围的年份数据
        
        // 初始化农历月份和日期数据
        self.nongLiMonths = @[@"正月", @"二月", @"三月", @"四月", @"五月", @"六月", @"七月", @"八月", @"九月", @"十月", @"冬月", @"腊月"];
        self.nongLiDays = @[@"初一", @"初二", @"初三", @"初四", @"初五", @"初六", @"初七", @"初八", @"初九", @"初十", @"十一", @"十二", @"十三", @"十四", @"十五", @"十六", @"十七", @"十八", @"十九", @"二十", @"廿一", @"廿二", @"廿三", @"廿四", @"廿五", @"廿六", @"廿七", @"廿八", @"廿九", @"三十"];
        
        
        // 初始化农历月份和日期数据
        self.yangLiMonths = @[@"1月", @"2月", @"3月", @"4月", @"5月", @"6月", @"7月", @"8月", @"9月", @"10月", @"11月", @"12月"];
        self.yangLiDays = @[@"1日", @"2日", @"3日", @"4日", @"5日", @"6日", @"7日", @"8日", @"9日", @"10日", @"11日", @"12日", @"13日", @"14日", @"15日", @"16日", @"17日", @"18日", @"19日", @"20日", @"21日", @"22日", @"23日", @"24日", @"25日", @"26日", @"27日", @"28日", @"29日", @"30日", @"31日"];
        
        
        // 创建UIPickerView
        self.pickerView = [[UIPickerView alloc] init];
        self.pickerView.dataSource = self;
        self.pickerView.delegate = self;
        
        // 设置pickerView的位置和尺寸
        self.pickerView.frame = CGRectMake(0, 50, screenWigth, 200);
        self.pickerView.backgroundColor = [UIColor whiteColor];
        // 将pickerView添加到视图中
        [self addSubview:self.pickerView];
        [self changeDataArray];
        
        
        
    }
    return self;
}

- (NSArray *)generateYearsArray {
    NSMutableArray *yearsArray = [NSMutableArray array];
    
    // 生成一定范围的年份数据，这里以前后各20年为例
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *currentDateComponents = [calendar components:NSCalendarUnitYear fromDate:[NSDate date]];
    NSInteger currentYear = [currentDateComponents year];
    
    for (NSInteger year = currentYear - 40; year <= currentYear + 40; year++) {
        NSInteger tianGanIndex = (year - 4) % 10; // 计算天干的索引
        NSString *tianGan = self.tianGanArray[tianGanIndex];
        NSInteger diZhiIndex = (year - 4) % 12; // 计算地支的索引
        NSString *diZhi = self.diZhiArray[diZhiIndex];
        [self.nongliYears addObject:[NSString stringWithFormat:@"%ld(%@%@年)",(long)year,tianGan,diZhi]];
        [yearsArray addObject:@(year)];
        
    }
    
    return yearsArray;
}

#pragma mark - UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return self.dataArray.count;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    NSArray *arr = self.dataArray[component];
    return arr.count;
}


#pragma mark - UIPickerViewDelegate

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *label = (UILabel *)view;
    if (!label) {
        label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentCenter;
    }
    
    label.font = [UIFont systemFontOfSize:16.0];
    NSArray *arr = self.dataArray[component];
    label.text = [NSString stringWithFormat:@"%@",arr[row]];
    
    
    return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
  
    
    if(self.showYear){
        
        if(self.isNongLi){
            
//            // 获取选定的年、月、日
            NSInteger selectedYear = [[self.years objectAtIndex:[pickerView selectedRowInComponent:0]] integerValue];
            NSCalendar *calendar1 = [NSCalendar currentCalendar];
            NSDateComponents * components1 = [[NSDateComponents alloc]init];
            components1.year = selectedYear;
            //取年中，判断阳历年大部分是什么农历年
            components1.month = 6;
            NSDate *date = [calendar1 dateFromComponents:components1];
            
            
            NSInteger selectedMonth = [pickerView selectedRowInComponent:1] + 1; // 月份是从1开始的
            NSInteger selectedDay = [pickerView selectedRowInComponent:2] + 1; // 日期是从1开始的
            NSCalendar * calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
            NSDateComponents * components = [[NSDateComponents alloc]init];
            
            NSDateComponents * dateComponents = [calendar components:(NSCalendarUnitYear) fromDate:date];
            components.year = dateComponents.year;
            components.month = selectedMonth;
            components.day = selectedDay;
            self.currentDate = [calendar dateFromComponents:components];
            
        }else{
            
            // 获取选定的年、月、日
            NSInteger selectedYear = [[self.years objectAtIndex:[pickerView selectedRowInComponent:0]] integerValue];
            NSInteger selectedMonth = [pickerView selectedRowInComponent:1] + 1; // 月份是从1开始的
            NSInteger selectedDay = [pickerView selectedRowInComponent:2] + 1; // 日期是从1开始的
            // 构建一个NSDate对象
            NSCalendar *calendar = [NSCalendar currentCalendar];
            NSDateComponents * dateComponents = [[NSDateComponents alloc]init];
            dateComponents.year = selectedYear;
            dateComponents.month = selectedMonth;
            dateComponents.day = selectedDay;
            self.currentDate = [calendar dateFromComponents:dateComponents];
        }
    }else{
        NSInteger selectedMonth = [pickerView selectedRowInComponent:0] + 1; // 月份是从1开始的
        NSInteger selectedDay = [pickerView selectedRowInComponent:1] + 1; // 日期是从1开始的
        
        
        // 构建一个NSDate对象
        NSCalendar *calendar = [NSCalendar currentCalendar];
        if(self.isNongLi){
            calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
        }
        NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
        
        // 获取年份
        NSDateComponents *components = [calendar components:NSCalendarUnitYear fromDate:self.currentDate];
        dateComponents.year = [components year];
        dateComponents.month = selectedMonth;
        dateComponents.day = selectedDay;
        self.currentDate = [calendar dateFromComponents:dateComponents];
    }
    
    if (component==self.dataArray.count-2) {
        // 如果选中的是月份列，更新日期列的天数
        NSInteger selectedMonth = row + 1; // 月份是从1开始的
        NSArray *arr = [self generateDaysArrayForMonth:selectedMonth];
        self.dataArray[self.dataArray.count-1] = arr;
        [pickerView reloadComponent:self.dataArray.count-1];
    }
    
}


#pragma mark 公历或者农历 selectedIndex= 0 为公历，1为农历
- (void)segmentedControlValueChanged:(UISegmentedControl *)sender {
    NSInteger selectedIndex = sender.selectedSegmentIndex;
    // 执行与选中项相关的操作
    self.isNongLi = selectedIndex==0 ?NO:YES;
    [self changeDataArray];
    
}

#pragma mark 是否显示年份
- (void)changeSelect:(UIButton *)but{
    
    but.selected = !but.selected;
    self.showYear = but.selected;
    [self changeDataArray];
    
}

#pragma mark 修改选择器源数据
- (void)changeDataArray{
    
    [self.dataArray removeAllObjects];
    
    if(self.isNongLi){
        if(self.showYear){
            [self.dataArray addObject:self.nongliYears];
        }
        [self.dataArray addObject:self.nongLiMonths];
    }else{
        if(self.showYear){
            [self.dataArray addObject:self.years];
        }
        [self.dataArray addObject:self.yangLiMonths];
    }
    
    // 获取年份
    NSCalendar *calendar1 = [NSCalendar currentCalendar];
    if(self.isNongLi){
        calendar1 = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
    }
    NSDateComponents *components1 = [calendar1 components:NSCalendarUnitMonth fromDate:self.currentDate];
    NSInteger month =components1.month;
    NSArray *array =[self generateDaysArrayForMonth:month];
    [self.dataArray addObject:array];
    [self.pickerView reloadAllComponents];
    [self scrollToCurrentDate];
    
}

#pragma mark 选择当前日期
- (void)scrollToCurrentDate{
    
    // 设置默认选择当前日期
    NSDateComponents *currentDateComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self.currentDate];
    NSInteger currentYear = [currentDateComponents year];
    if(self.isNongLi){
        currentDateComponents = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese] components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self.currentDate];
        
    }
    NSInteger nongliYear = [currentDateComponents year];
    NSInteger currentMonth = [currentDateComponents month];
    NSInteger currentDay = [currentDateComponents day];
    if(self.showYear){
        if(self.isNongLi){
            [self.pickerView selectRow:nongliYear inComponent:0 animated:NO]; // 年份选择
        }else{
            [self.pickerView selectRow:[self.years indexOfObject:@(currentYear)] inComponent:0 animated:NO]; // 年份选择
        }
        [self.pickerView selectRow:currentMonth - 1 inComponent:1 animated:NO]; // 月份选择
        [self.pickerView selectRow:currentDay - 1 inComponent:2 animated:NO]; // 日期选择
        
    }else{
        [self.pickerView selectRow:currentMonth - 1 inComponent:0 animated:NO]; // 月份选择
        [self.pickerView selectRow:currentDay - 1 inComponent:1 animated:NO]; // 日期选择
        
    }
    
    
}

#pragma mark 获取月的天数
- (NSArray *)generateDaysArrayForMonth:(NSInteger)month {
    // 生成包含农历日期和24节气的数组
    NSMutableArray *daysArray = [NSMutableArray array];
    
    NSDateComponents *components = [[NSDateComponents alloc] init];

    //获取月份
    components.month = month;
    
    // 获取当前月份的天数
    if(self.isNongLi){
        NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
        NSDateComponents *components1 = [calendar components:NSCalendarUnitYear fromDate:self.currentDate];
        components.year = [components1 year];
        NSRange daysRange = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[calendar dateFromComponents:components]];
        
        // 生成农历日期
        for (NSInteger day = 0; day < daysRange.length; day++) {
            [daysArray addObject:[NSString stringWithFormat:@"%@", self.nongLiDays[day]]];
        }
    }else{
        NSCalendar *calendar = [NSCalendar currentCalendar];
        // 获取年份
        NSDateComponents *components1 = [calendar components:NSCalendarUnitYear fromDate:self.currentDate];
        components.year = [components1 year];
        
        NSRange daysRange = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[calendar dateFromComponents:components]];
        // 生成农历日期
        for (NSInteger day = 1; day <= daysRange.length; day++) {
            [daysArray addObject:[NSString stringWithFormat:@"%ld日", (long)day]];
        }
    }
    return daysArray;
}

- (void)queding{
    
    if(self.finishBlock){
        self.finishBlock(self.currentDate);
    }
    
    
}


@end
